<template>
  <div class="upload" v-loading="loading" element-loading-text="上传中">
    <el-row :gutter="20">
      <el-col :span="24" :offset="0">
        <el-upload class="upload-demo" ref="upload" action="" :http-request="httpRequest" :file-list="fileList"
          :on-remove="handleRemove" :before-upload="beforeAvatarUpload" :multiple="limit == 1 ? false : true"
          :limit="limit" :on-exceed="handleExceed" :disabled="!this.switch">
          <div class="upload__title">
            <span class="red" v-if="this.require">*</span>
            <span :style="{color:color}">{{titleName}}</span>&#12288;
            <el-button size="small" type="primary" v-if="this.switch">点击上传</el-button>
          </div>
          <div slot="tip" class="upload__tip">
            只能上传 <span class="upload__span">“ {{accept.join('，')}} ”</span> 格式文件，且不超过{{size}}M
          </div>
          <div slot="file" slot-scope="{file}" class="upload__list">
            <div v-for="(item,index) in fileList" :key="index">
              <div class="fileLeft"> {{item.name}} </div>
              <div class="fileRight">
<!--                <look-pdf1 :buttonName="'查看'" :size="'mini'" :url="file.url" style="margin-right:10px">-->
<!--                </look-pdf1>-->
                <el-button type="primary" size="mini" @click="open(file.url)">查看</el-button>
                <el-button type="primary" size="mini" @click="download(file.url)">下载</el-button>
                <el-button type="danger" size="mini" @click="handleRemove">删除</el-button>
              </div>
            </div>
          </div>
        </el-upload>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import LookPdf1 from './LookPdf1.vue'
export default {
  name: 'Upload',
  components: {
    LookPdf1
  },
  model: {
    prop: 'url',
    event: 'change'
  },
  props: {
    titleName: {
      type: String,
      default: () => {
        return '文件上传'
      }
    },
    require: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    switch: {
      type: Boolean,
      default: () => {
        return true
      }
    },
    accept: {
      type: Array,
      default: () => {
        return ['pdf']
      }
    },
    size: {
      type: Number,
      default: () => {
        return 50
      }
    },
    // 制作了一个文件的上传，多文件功能废弃
    limit: {
      type: Number,
      default: () => {
        return 1
      }
    },
    url: {
      // type: [String, Object],
      type: String,
      default: () => {
        return ''
      }
    },
    // 标题颜色
    color: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  data () {
    return {
      loading: false,
      pdfShow: false,
      pdfSize: '50%',
    }
  },
  created () {

  },
  mounted () {
    this.init()
  },
  methods: {
    init () {

    },
    // 校验
    beforeAvatarUpload (file) {
      const houzui = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase()
      let type = false
      for (let i = 0; i < this.accept.length; i++) {
        const temp = this.accept[i]
        if (houzui == temp) {
          type = true;
          break;
        }
      }

      const limitMax = file.size / 1024 / 1024 < this.size;

      const limitMin = file.size != 0

      if (!type) {
        this.$tips.error('当前格式 ' + houzui + ' 上传文件只能是 ' + this.accept.join('，') + ' 格式');
        return false;
      }
      if (!limitMax) {
        this.$tips.error('上传文件大小不能超过 ' + this.size + ' M');
        return false;
      }

      if (!limitMin) {
        this.$tips.error('上传文件大小不能等于0k');
        return false;
      }

      return type && limitMax && limitMin;
    },
    // 上传
    async httpRequest (file, fileList) {
      // 上传时间，文件名称
      let fileName = ''
      let point = file.file.name.lastIndexOf('.')
      const timestamp = new Date().getTime();
      const random = Math.floor(Math.random() * 999999);
      // 时间戳 + 6位随机数
      fileName = timestamp + file.file.name.slice(0, point) + random + file.file.name.slice(point, file.file.name.length)
      const res = await this.$http('uploadSign', {
        fileName: fileName,
        filePath: 'house/Wl',
        timestamp: timestamp
      })
      const sign = res.sign
      let reader = new FileReader();
      reader.readAsDataURL(file.file);
      reader.onload = async (e) => {
        this.loading = true
        const file = e.target.result.substring(e.target.result.indexOf(',') + 1);
        const res1 = await this.$http('uploadBase', {
          fileName: fileName,
          filePath: 'house/Wl',
          timestamp: timestamp,
          sign: sign,
          file: file,
        })
        if (res1) {
          this.fileList.push({
            name: fileName,
            url: res1
          })
          this.$emit('change', res1);
        } else {
          this.loading = false
          return
        }
        this.loading = false
      }
    },
    // 成功
    onSuccess (response, file, fileList) {
      console.log(response, file, fileList, 'success');
    },
    // 失败
    onError (file, fileList) {
      console.log(file, fileList, 'error');
    },
    // 下载
    download (url) {
      location.href = url
    },
    open (url) {
      window.open(url);
    },
    // 删除
    handleRemove (file) {
      let fileList = this.$refs.upload.uploadFiles;
      let index = fileList.findIndex((fileItem) => {
        return fileItem.uid === file.uid;
      });
      fileList.splice(index, 1);
      this.$emit('change', '')
    },
    // 文件个数限制提示
    handleExceed () {
      this.$tips.warning('最多可以上传 ' + this.limit + ' 个文件')
    },
    changeSize (size) {
      this.pdfSize = size + '%'
    },
    cancel () {
      this.pdfShow = false
      this.pdfSize = '50%'
    }
  },
  computed: {
    fileList () {
      // 判断数组是否应该为空
      if (this.url == '' || this.url == '无') {
        return [];
      }
      // 加载名字截取，新老版本
      if (this.url.indexOf('?op=OPEN') > -1) {
        const start = this.url.lastIndexOf('/') + 1;
        const end = this.url.lastIndexOf('?op=OPEN');
        const name = this.url.substring(start, end);
        return [{ name, url: this.url }];

      } else {
        const start = this.url.lastIndexOf('/') + 1 + 13;
        const end = this.url.length;
        const name = this.url.substring(start, end);
        return [{ name, url: this.url }];
      }
      // 数组动态变化

    }
  }
}
</script>
<style lang="scss" scoped>
.upload {
  position: relative;
  width: 100%;
  margin: 5px;
  &__title {
    display: inline-block;
    width: 100%;
    font-weight: 700;
    font-size: 15px;
    text-align: left;
  }
  &__tip {
    // margin-top: 30px;
    font-size: 8px;
    color: #969799;
  }
  &__span {
    font-size: 10px;
    color: #155bd4;
  }
  &__list {
    margin-top: 0px !important;
    .fileLeft {
      font-size: 16px;
      // 超长换行
      word-wrap: break-word;
      word-break: break-all;
    }
    .fileRight {
      // display: flex;
      text-align: right;
    }
  }
}
.upload-demo {
  margin-top: 0px !important;
}
.red {
  color: red;
  margin-right: 5px;
}
</style>
